<script setup lang="ts">
import { computed, defineEmits, defineProps, ref, watch } from 'vue'
import { NButton, NDescriptions, NDescriptionsItem, NInput, NSelect, NSpace, NSwitch, useMessage } from 'naive-ui'
import type { IPdfMeta } from '@/views/pdf/DataModel'
const props = defineProps<{
  pdfMetaList: IPdfMeta[] | null
  isEditingMeta: boolean
  selectedIds: number
}>()
const emit = defineEmits<{
  (e: 'updatePdfMetaList', updatedPdfMeta: IPdfMeta): void
  (e: 'toggleEditing', isEditingMeta: boolean): void
}>()
// 提示信息函数
const message = useMessage()
const selectedIds = computed(() => props.selectedIds)
const initialPdfMeta: IPdfMeta = {
  pdfUuid: 0,
  hubUuid: 0,
  tags: [],
  doi: '',
  title: '',
  keyword: [],
  author: [],
  affiliation: [],
  publicTime: '',
  publicJournal: '',
  isConference: false,
  conferenceName: '',
  conferenceTime: '',
  staticUrl: '',
}

const editedPdfMeta = ref<IPdfMeta>(initialPdfMeta)
const clearEditedPdfMeta = () => {
  editedPdfMeta.value = { ...initialPdfMeta }
}
const originalPdfMeta = ref<IPdfMeta | null>(null)
// TODO: 后期可能替换为获取该知识库中所有的标签列表
const customTagsOption = ref([
  {
    label: '标签1',
    value: '标签1',
  },
  {
    label: '标签2',
    value: '标签2',
  },
])
watch(selectedIds, () => {
  const selectedPdfMeta = getSelectedPdfMeta()

  if (selectedPdfMeta) {
    // 更新 editedPdfMeta 的值为选定的元信息
    editedPdfMeta.value = { ...selectedPdfMeta }
    originalPdfMeta.value = { ...selectedPdfMeta }
  }
  else {
    // 没有找到那么需要重置 editedPdfMeta 的值
    clearEditedPdfMeta()
  }
}, { immediate: true })

function getSelectedPdfMeta(): IPdfMeta | undefined {
  if (Array.isArray(props.pdfMetaList))
    return props.pdfMetaList.find(meta => meta.pdfUuid === props.selectedIds)

  return undefined
}

const handleSaveMeta = () => {
  saveEditedPdfMeta()
  emit('toggleEditing', false) // 将 isEditingMeta 设置为 false，并传递给父组件
}

const handleCancelEdit = () => {
  // 恢复元数据
  if (originalPdfMeta.value) {
    editedPdfMeta.value = { ...originalPdfMeta.value }
    emit('updatePdfMetaList', originalPdfMeta.value)
  }
  emit('toggleEditing', false) // 取消编辑时将 isEditingMeta 设置为 false
}

async function saveEditedPdfMeta() {
  const selectedPdfMeta = getSelectedPdfMeta()

  if (selectedPdfMeta) {
    const updatedPdfMeta = { ...selectedPdfMeta, ...editedPdfMeta.value }
    emit('updatePdfMetaList', updatedPdfMeta)
    console.log('保存编辑后的元信息:', updatedPdfMeta)
    // 上传到服务器
    const url = 'http://localhost:8088/update'
    const data = updatedPdfMeta
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
      mode: 'cors', // 允许跨域
    })
    if (!response.ok) {
      message.error('网络错误；修改失败')
      return
    }
    // 查看是否上传成功
    const tmpData = await response.json()
    if (!tmpData || tmpData.code === 0) {
      message.error(`修改失败:${tmpData.msg}`)
      return
    }
    message.success('修改成功')
  }
  else if (originalPdfMeta.value) {
    // 如果取消了编辑，恢复原始数据
    emit('updatePdfMetaList', originalPdfMeta.value)
    originalPdfMeta.value = null // 清空原始数据副本
    // console.log('已恢复原始数据:', originalPdfMeta.value)
  }
}
</script>

<template>
  <div>
    <NDescriptions
      label-placement="left" label-align="left" title="PDF元信息" :column="1" bordered
      label-style="width:12em"
    >
      <!-- 自定义标签列表 -->
      <NDescriptionsItem label="自定义标签列表">
        <NSelect
          v-model:value="editedPdfMeta.tags" :disabled="!props.isEditingMeta" class="custom-tags" filterable
          multiple tag :options="customTagsOption"
        />
      </NDescriptionsItem>

      <!-- DOI -->
      <NDescriptionsItem label="DOI">
        <NInput v-model:value="editedPdfMeta.doi" :disabled="!props.isEditingMeta" />
      </NDescriptionsItem>
      <!-- 论文标题 -->
      <NDescriptionsItem label="论文标题">
        <NInput v-model:value="editedPdfMeta.title" :disabled="!props.isEditingMeta" />
      </NDescriptionsItem>
      <!-- 关键词 -->
      <NDescriptionsItem label="关键词">
        <NSelect
          v-model:value="editedPdfMeta.keyword" :disabled="!props.isEditingMeta" class="custom-tags" filterable
          multiple tag
        />
      </NDescriptionsItem>
      <!-- 作者 -->
      <NDescriptionsItem label="作者">
        <NSelect
          v-model:value="editedPdfMeta.author" :disabled="!props.isEditingMeta" class="custom-tags" filterable
          multiple tag
        />
      </NDescriptionsItem>
      <!-- 所在单位 -->
      <NDescriptionsItem label="所在单位">
        <NSelect
          v-model:value="editedPdfMeta.affiliation" :disabled="!props.isEditingMeta" class="custom-tags"
          filterable multiple tag
        />
      </NDescriptionsItem>
      <!-- 出版时间 -->
      <NDescriptionsItem label="出版时间">
        <NInput v-model:value="editedPdfMeta.publicTime" :disabled="!props.isEditingMeta" />
      </NDescriptionsItem>
      <!-- 出版刊物 -->
      <NDescriptionsItem label="出版刊物">
        <NInput v-model:value="editedPdfMeta.publicJournal" :disabled="!props.isEditingMeta" />
      </NDescriptionsItem>
      <!-- 是否是会议 -->
      <NDescriptionsItem label="是否是会议">
        <NSwitch v-model:value="editedPdfMeta.isConference" :disabled="!props.isEditingMeta" />
      </NDescriptionsItem>

      <!-- 会议名称 -->
      <NDescriptionsItem label="会议名称">
        <NInput v-model:value="editedPdfMeta.conferenceName" :disabled="!props.isEditingMeta" />
      </NDescriptionsItem>
      <!-- 会议时间 -->
      <NDescriptionsItem label="会议时间">
        <NInput v-model:value="editedPdfMeta.conferenceTime" :disabled="!props.isEditingMeta" />
      </NDescriptionsItem>
      <!-- 静态链接 -->
      <NDescriptionsItem label="静态链接">
        <NInput v-model:value="editedPdfMeta.staticUrl" :disabled="true" />
      </NDescriptionsItem>
    </NDescriptions>
    <NSpace>
      <NButton v-show="props.isEditingMeta" strong secondary type="primary" @click="handleSaveMeta">
        保存元信息
      </NButton>
      <NButton v-show="props.isEditingMeta" strong secondary type="primary" @click="handleCancelEdit">
        取消编辑
      </NButton>
    </NSpace>
  </div>
</template>

<style lang="less" scoped>
.custom-tags {
  min-width: 140px;
}
</style>
